package com.example.commons.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer() {
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        return container;
    }

    @Bean
    KeyExpirationEventMessageListener keyExpirationListener() {
        return new KeyExpirationEventMessageListener(redisMessageListenerContainer()) {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                // 这里处理key过期事件
                String expiredKey = message.toString();
                System.out.println("Key过期了： " + expiredKey);
            }
        };
    }
}